package com.bq.gametrade.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.adapter.AddressBookListAdapter;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.AddressBook;
import com.bq.gametrade.bean.AddressBookDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.utils.Base64Util;
import com.bq.gametrade.utils.PermissionsChecker;
import com.bq.gametrade.widget.PromptAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddressBookActivity extends BaseActivity implements View.OnClickListener {

    private TextView title;
    private ImageView back;
    private ImageView add;
    private LinearLayout layAddFriend;
    private ListView addressBookList;

    private LinearLayout layPrompt;
    private TextView tvPormpt;

    private ArrayList<AddressBookDetails> mList = new ArrayList<>();
    private AddressBookListAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addressbook);
        myCheckPermission();
        initView();
//        getPhoneContacts();
    }

    private void initView() {
        title = serchViewById(R.id.title_name);
        title.setText("通讯录");
        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        add = serchViewById(R.id.iv_add);
        add.setOnClickListener(this);
        layAddFriend = serchViewById(R.id.lay_addFriend);
        layAddFriend.setOnClickListener(this);
        tvPormpt = serchViewById(R.id.tv_pormpt);
        layPrompt = serchViewById(R.id.lay_prompt);

        addressBookList = serchViewById(R.id.lv_addressBook);
        adapter = new AddressBookListAdapter(AddressBookActivity.this, mList);
        addressBookList.setAdapter(adapter);
        addressBookList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String name;
                if (!mList.get(position).userName.equals("")) {
                    name = mList.get(position).userName;
                } else {
                    name = "还没有昵称";
                }
                Intent intent = new Intent(AddressBookActivity.this, FriendInformationActivity.class);
                intent.putExtra("friendBqAccount", mList.get(position).bqAccount);
                intent.putExtra("friendAccount", mList.get(position).userId);
                intent.putExtra("strFriendHeadImage", mList.get(position).headimg);
                intent.putExtra("friendName", name);
                startActivity(intent);
            }
        });
        adapter.setOnItemClickLitener(new AddressBookListAdapter.OnAddFriendListener() {
            @Override
            public void onAdd(int position) {
                if (mList.get(position).userId.equals(application.getUserInfo().account)) {
                    toastShow("不能添加自己为好友");
                    return;
                }
                addFriend(mList.get(position).userId);
            }
        });
    }

    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.iv_add:
                startActivity(new Intent(AddressBookActivity.this, FriendAddActivity.class));
                break;
            case R.id.lay_addFriend:
                startActivity(new Intent(AddressBookActivity.this, FriendAddActivity.class));
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private List<String> mPhoneDats = new ArrayList<>();

    private void getPhoneContacts() {

        showSpotsDialog("加载好友信息···");
        String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER};
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                cols, null, null, null);
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            // 取得联系人名字
//            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
//            String userName = cursor.getString(nameFieldColumnIndex);

            String phoneNumber = cursor.getString(numberFieldColumnIndex);
//            Toast.makeText(this, name + " " + number, Toast.LENGTH_SHORT).show();
            if (phoneNumber.replace(" ", "").replace("+86", "").replace("029", "").length() == 11) {
                mPhoneDats.add("'" + phoneNumber.replace(" ", "").replace("+86", "").replace("029", "") + "'");
            }

        }
        cursor.close();
        String phoneList;
        if (mPhoneDats.toString().length() < 4050) {
            phoneList = mPhoneDats.toString().replace("[", "").replace(" ", "").replace("]", "");
        } else {
            phoneList = mPhoneDats.toString().replace("[", "").replace(" ", "").replace("]", "").substring(0, 4050);
        }
        if (phoneList.length() > 11) {
            getFriendInfo(phoneList);

        } else {
            toastShow("您还没有联系人");
            closeSpotsDialog();
        }
    }

    private void getFriendInfo(String phoneList) {

        Map<String, String> params = new HashMap<>();
        params.put("token", application.getUserInfo().token);
        params.put("tels", phoneList);
        VRHttp.getAddressBookList(AddressBookActivity.this, HttpLink.SEND_USERPHONE_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                if (response != null) {
                    AddressBook userFriend = (AddressBook) response;
                    if (userFriend.status.equals("0")) {
                        mList = userFriend.account_list;
                        if (mList.size() > 0) {
                            layPrompt.setVisibility(View.GONE);
                            adapter.setData(mList);
                            adapter.notifyDataSetChanged();
                        } else {
                            layPrompt.setVisibility(View.VISIBLE);
                            layPrompt.setVisibility(View.VISIBLE);
                            tvPormpt.setVisibility(View.VISIBLE);
                            tvPormpt.setText("您还比起好友哦!快去邀请吧");
                        }
                    } else if (userFriend.status.equals("99")) {
                        toastShow("登录超时");
                        application.setUserInfo(null);
                        startActivity(new Intent(AddressBookActivity.this, LoginActivity.class));
                    } else if (userFriend.status.equals("98")) {
                        toastShow("您的账号已在其它设备登录，请重新登录修改您的密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(AddressBookActivity.this, LoginActivity.class));
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }

    private void addFriend(String account) {


        Map<String, String> params = new HashMap();
        params.put("token", application.getUserInfo().token);
        params.put("friendId", account);
        params.put("remark", "");
        showSpotsDialog("正在添加····");
        VRHttp.getResponse(AddressBookActivity.this, HttpLink.ADD_FRIENDS_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    try {
                        JSONObject object = new JSONObject(response.toString());
                        String status = object.getString("status");
                        if (status.equals("0")) {
                            String message = object.getString("message");
                            toastShow(Base64Util.decodeStr(message));
                            finish();
                        } else if (status.equals("1")) {
                            String message = object.getString("message");
                            toastShow(Base64Util.decodeStr(message));
                        } else if (status.equals("99")) {
                            toastShow("登录超时请重新登陆");
                            application.setUserInfo(null);
                            startActivity(new Intent(AddressBookActivity.this, LoginActivity.class));
                        } else if (status.equals("98")) {
                            toastShow("您的账号已在其它设备登录，请重新登录修改您的密码");
                            application.setUserInfo(null);
                            startActivity(new Intent(AddressBookActivity.this, LoginActivity.class));
                            finish();
                        } else {
                            toastShow("添加好友失败！");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }

    private static final int REQUEST_PERM = 151;

    /***
     * 动态授权
     */
    public void myCheckPermission() {

        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{
                    Manifest.permission.READ_CONTACTS,
                    Manifest.permission.WRITE_CONTACTS,
            };
            ActivityCompat.requestPermissions(this, mPermissionList, REQUEST_PERM);
        }else {
            getPhoneContacts();
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_PERM: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getPhoneContacts();

                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    new PromptAlertDialog(AddressBookActivity.this).builder().setTitle("提示").setTouchOutsideCanceled(true)
                            .setMsg("授权失败！就不能查询到通讯录中是否有好友也在使用比奇交易")
                            .setPositiveButton("重新授权", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    myCheckPermission();
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                }
                return;
            }
        }
    }
}
